package com.framework.network.interceptor.commoninter

import android.content.Context
import com.framework.network.manager.NetworkManager
import com.framework.network.utils.JsonToMapUtil.gsonToMap
import com.google.gson.Gson
import okhttp3.FormBody
import okhttp3.MultipartBody
import okhttp3.Request
import okhttp3.RequestBody
import okio.Buffer
import java.nio.charset.Charset

/**
 * @ClassName: PostRequestParams
 * @Description: POST请求
 * @Author: you
 */
class PostRequestParams(private val context: Context) : IRequestParam {
    override fun getRequest(request: Request, context: Context): Request {
        val body = request.body
        body?.run {
            if (this is FormBody) {//传统表单
                return request.newBuilder().post(formBody(this).build()).build()
            }
            if (this is MultipartBody) {//文件提交--用到了再添加
                return request
            }
            if (this is RequestBody) {//json提交---是RequestBody的一个匿名子类
                return request.newBuilder().post(jsonBody(this)).build()
            }
        }
        return request
    }

    /**
     * 传统的form表单
     */
    private fun formBody(formBody: FormBody): FormBody.Builder {
        val bodyBuilder = FormBody.Builder()
        for (i in 0..formBody.size) {
            bodyBuilder.addEncoded(formBody.encodedName(i), formBody.encodedValue(i))
        }

        NetworkManager.getInstance().create().commonMap?.forEach {
            it.run {
                bodyBuilder.addEncoded(key, value.toString())
            }
        }

        return bodyBuilder
    }

    /**
     * json提交
     */
    private fun jsonBody(requestBody: RequestBody): RequestBody {
        var content: String? = ""
        requestBody.let {
            val buffer = Buffer()
            it.writeTo(buffer)
            var charset: Charset? = Charset.forName("UTF-8")
            val contentType = it.contentType()
            contentType?.let {
                charset = contentType.charset(Charset.forName("UTF-8"))
            }
            content = buffer.readString(charset!!)
        }
        val hashMap = if (content.isNullOrBlank().not()) {
            gsonToMap(content ?: "")
        } else {
            hashMapOf()
        }
        return if (hashMap != null) {
            NetworkManager.getInstance().create().commonMap?.forEach {
                it.run {
                    hashMap[key] = value
                }
            }
            val newJson = Gson().toJson(hashMap).toString()
            if (newJson.isNotBlank()) {
                PostJsonBody.create(newJson)
            } else {
                requestBody
            }
        } else {
            requestBody
        }
    }

}